package cn.ac.cintcm.prespring.tree;

import java.io.IOException;
import java.util.List;

import cn.ac.cintcm.prespring.util.FileUtil;
import cn.ac.cintcm.prespring.util.IndexFile;
import cn.ac.cintcm.prespring.util.NameIndex;
import cn.ac.cintcm.prespring.util.NumberAllocation;

public class FileLadder {
    private IndexFile index;
    private NameIndex elements;
    private NameIndex items;
    private WebTree wt;
   
    public static void main(String[] args) throws IOException {
        //findAll();
        FileLadder ld = new FileLadder("PRES_FJ_ZYS.txt", "presIndex.txt", "herbsIndex.txt");
        //070232????????#?059611?????
        FileUtil.write(ld.findLadder("059611"), "059611.htm");
    }
    
    public FileLadder(String iefName, String ifName, String efName) throws IOException {
        index = new IndexFile(iefName);
        wt = new WebTree(efName, ifName);
    }
    
    public FileLadder(IndexFile ifl, NameIndex names, NameIndex elements) throws IOException {
        index = ifl;
        wt = new WebTree(names, elements);
    }
    
    /**
     * 
     * @param file
     * @throws IOException
     */
    public FileLadder(String file) throws IOException {
        List<String> itemList = FileUtil.read(file);
        if (itemList != null) {
            NumberAllocation nb = new NumberAllocation();
            for (String s : itemList) {
                nb.allocateNumber(s);
            }
            index = nb.getIndex();
            elements = nb.getElements();
            items = nb.getItems();
            wt = new WebTree(elements, items);
        }
    }
    
    public StringBuilder findLadder(String idStr) throws IOException {
        int id = Integer.parseInt(idStr);
        Ladder ld = new Ladder(index);
        VisitMemory vm = new VisitMemory(id);
        vm = ld.getLadder(idStr);
        
        wt.setIndex(id, index);
        wt.setTree(vm);
        return wt.createWebTree();
    }

}
